/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-maintain
*
* @File name : MaintainController.java
*
* @Author : Administrator
*
* @Date : 2017年3月8日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年3月8日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.maintain.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dms.dto.IfMessage;
import org.marketing.common.dms.dto.ResultMessage;
import org.marketing.common.dto.maintain.CarModelDto;
import org.marketing.common.dto.maintain.MaintainDealerDto;
import org.marketing.common.dto.maintain.MaintainDto;
import org.marketing.common.dto.maintain.MaintainFrecordDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.yonyou.gmmc.service.maintain.constant.MaintainConstant;
import com.yonyou.gmmc.service.maintain.model.ApplyConfirm;
import com.yonyou.gmmc.service.maintain.service.MaintainService;
import com.yonyou.gmmc.service.maintain.model.MaintainInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author Administrator
 * @date 2017年3月8日
 */
@RestController
@RequestMapping(value = MaintainConstant.BASE_PATH + "/" + MaintainConstant.VERSION)
@Api("养修预约")
public class MaintainController {

    private Logger          logger = Logger.getLogger(MaintainController.class);

    @Autowired
    private MaintainService maintainService;

    /**
     * 取得空余时间-不包含工位信息，分时段的。每半小时为一个时段
     * 
     * @author WangHuicheng
     * @date 2016年12月7日
     * @param dealerCode
     * @param appDay
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/simple", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation(value = "取得空余时间", notes = "取得空余时间")
    public List<String> getFreeTimeNoWorkStation(@RequestParam("dealerCode") String dealerCode) {
        List<String> timeList = new ArrayList<>();
        try {
            // 查询经销商闲时
            this.logger.info("FreeTime!");
            timeList = maintainService.getFreeTimeNoWorkStation(dealerCode);
        } catch (Exception e) {
            this.logger.info("错误");
            this.logger.error(e.getMessage(), e);
        }
        return timeList;

    }

    /**
     * 保存养修预约信息
     * 
     * @author QianKun
     * @date 2017年3月8日
     * @param maintainDto
     * @return
     */
    @RequestMapping(value = "/saveMaintain", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "保存养修预约", notes = "保存养修预约")
    public Map<String, Object> saveMaintain(@RequestBody MaintainDto maintainDto,HttpServletRequest request) {
    	logger.info("1");
        String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
    	if(!CheckUtil.NullOrEmpty(userId)){
    		maintainDto.setUserId(userId);
    	}
        return maintainService.saveMaintain(maintainDto);
    }

    /**
     * @author QianKun 养修预约列表查询
     * @date 2016年11月17日
     * @param userId
     * @return
     */
    @RequestMapping(value = "/repairs", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "养修预约列表查询", notes = "养修预约列表查询")
    public List<MaintainDto> getMaintainData(HttpServletRequest request
    		,@RequestParam(value = "userId_",required = false,defaultValue = "") String userId_) {
    	String userId = "";
    	try {
    		if(!CheckUtil.NullOrEmpty(userId_)){
    			userId = userId_;
        	}else{
        		userId = request.getHeader(CommonConstant.HEAD_USER_ID);
        	}
    		return maintainService.getMaintainData(userId);
    	}  catch (Exception e) {
    		logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
    	}
    }

    /**
     * @author QianKun 养修预约详情查询
     * @date 2016年11月17日
     * @param resnId
     * @return
     */
    @RequestMapping(value = "/repairs/info", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "养修预约详情查询", notes = "养修预约详情查询")
    public List<MaintainDto> getMaintainDataById(@RequestParam("resnId") String resnId) {
        resnId = resnId.replaceAll("#", "").replaceAll("/", "");
        return maintainService.getMaintainDataById(resnId);
    }

    /**
     * 养修预约经销商，车辆信息查询
     * 
     * @author QianKun
     * @date 2017年2月17日
     * @param openId
     * @return
     */
    @RequestMapping(value = "/maintainSel", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "经销商，车辆信息查询", notes = "经销商，车辆信息查询")
    public List<MaintainDto> getMaintainSel(HttpServletRequest request,@RequestParam(value = "userId_",required = false,defaultValue = "") String userId_) {
    	String userId = "";
    	if(!CheckUtil.NullOrEmpty(userId_)){
    		userId = userId_;
    	}else{
    		userId = request.getHeader(CommonConstant.HEAD_USER_ID);
    	}
    	
        return maintainService.getMaintainSel(userId);
    }

    /**
     * 全部省/市查询 90011001：省,90011002：市
     * 
     * @author QianKun
     * @date 2017年2月21日
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/maintainDealerMap", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "全部省/市查询 ", notes = "全部省/市查询 ")
    public List<MaintainDealerDto> getMaintainDealerMap(@RequestParam("regionType") String regionType) {
        return maintainService.getMaintainDealerMap(regionType);
    }

    /**
     * 根据省查市
     * 
     * @author QianKun
     * @date 2017年3月1日
     * @param parentCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/SelectCityMap", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "根据省查市 ", notes = "根据省查市")
    public List<MaintainDealerDto> getSelectCityMap(@RequestParam("parentCode") String parentCode) {
        return maintainService.getSelectCityMap(parentCode);
    }

    /**
     * 养修搜索经销商城市
     * 
     * @author QianKun
     * @date 2017年2月21日
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/maintainSelectCity", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "养修搜索经销商城市 ", notes = "养修搜索经销商城市")
    public List<MaintainDealerDto> getSelectCity(@RequestParam("regionName") String regionName) {
        return maintainService.getSelectCity(regionName);
    }

    /**
     * 查询该城市下的经销商
     * 
     * @author QianKun
     * @date 2017年2月21日
     * @param tmAdministrationId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/maintainDealer", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "查询该城市下的经销商 ", notes = "查询该城市下的经销商")
    public List<MaintainDealerDto> getMaintainDealer(@RequestParam("regionName") String regionName,
                                                     @RequestParam("dealerCode") String dealerCode) {
        return maintainService.getMaintainDealer(regionName, dealerCode);
    }

    @RequestMapping(value = "/maintainDealers", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "查询该城市下的经销商(养修预约使用) ", notes = "查询该城市下的经销商(养修预约使用) ")
    public List<MaintainDealerDto> getMaintainDealers(@RequestParam("regionName") String regionName,
                                                      @RequestParam("dealerCode") String dealerCode) {
        return maintainService.getMaintainDealers(regionName, dealerCode);
    }

    /**
     * 搜索某经销商
     * 
     * @author QianKun
     * @date 2017年3月1日
     * @param regionCode
     * @param dealerName
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/searchDealer", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "搜索某经销商", notes = "搜索某经销商")
    public List<MaintainDealerDto> getSearchDealer(@RequestParam("dealerName") String dealerName) {
        return maintainService.getSearchDealer(dealerName);
    }

    @RequestMapping(value = "/searchDealers", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "搜索某经销商(养修预约使用) ", notes = "搜索某经销商(养修预约使用) ")
    public List<MaintainDealerDto> getSearchDealers(@RequestParam("dealerName") String dealerName) {
        return maintainService.getSearchDealers(dealerName);
    }

    /**
     * 根据微信ID查找出该用户下绑定的车辆信息
     * 
     * @author QianKun
     * @date 2017年3月8日
     * @param openId
     * @return
     */
    @RequestMapping(value = "getBindCarInfos", method = RequestMethod.GET)
    @ApiOperation(value = "根据微信ID查找出该用户下绑定的车辆信息", notes = "根据微信的OPENID查找该微信下面绑定的车辆信息")
    public List<CarModelDto> getCarInfoByOpenID(HttpServletRequest request) {
        String openId = request.getHeader(CommonConstant.HEADER_OPENID);
//        logger.info("我的OPENID为：" + openId);
        this.logger.info(this.getClass().getName() + "getCarInfoByOpenID:begin");
        this.logger.info("@RequestParam:" + openId);
        return maintainService.getCarInfoByOpenID(openId);
    }

    /**
     * 更新养修预约状态
     * 
     * @author WangHuicheng
     * @date 2016年11月25日
     * @param testdrivingAmFrecordDto
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateMaintainStatus", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "更新养修预约状态", notes = "更新养修预约状态")
    public @ResponseBody Map<String, Object> updateMaintainAppointStatus(@RequestBody @Valid MaintainFrecordDto maintainFrecordDto) {
        maintainService.updateMaintainStatus(maintainFrecordDto);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
        resultMap.put(ResultMsgConstants.ERR_MSG, "取消成功！");
        return resultMap;
    }

    /**
     * 维修预约确认
     * 
     * @author Administrator
     * @date 2017年3月25日
     * @param maintainDto
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/appointment/status", method = RequestMethod.POST)
    @ApiOperation(value = "维修预约确认", notes = "维修预约确认")
    public ResultMessage applyConfire(@RequestBody IfMessage<List<ApplyConfirm>> info) {
        ResultMessage message = new ResultMessage();
        // ----业务开始
        maintainService.applyConfire(info);
        // ----业务结束
        Map<String, String> map = new HashMap<>();
        map.put("reservationNO", info.getIfData().get(0).getReservationNO());
        List<Map<String, String>> list = new ArrayList<>();
        list.add(map);
        String result = JSON.toJSONString(list);
        message.setIfCode(info.getIfCode());
        message.setTransferNo(info.getTransferNo());
        message.setResult("200");
        message.setResultList(result);
        return message;
    }

    /**
     * 维修工单反馈接口
     * 
     * @author Administrator
     * @date 2017年3月25日
     * @param info
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/maintainorder", method = RequestMethod.POST)
    @ApiOperation(value = "维修工单反馈接口", notes = "维修工单反馈接口")
    public ResultMessage maintainInfo(@RequestBody IfMessage<List<MaintainInfo>> info) throws Exception {
    	IfMessage<List<MaintainInfo>> ifMessage = new IfMessage<List<MaintainInfo>>();
    	ifMessage.setDataCnt(info.getDataCnt());
    	ifMessage.setIfData(info.getIfData());
    	ifMessage.setIfCode(info.getIfCode());
    	ifMessage.setOccurtime(info.getOccurtime());
    	ifMessage.setTransferNo(info.getTransferNo());
    	ResultMessage message = new ResultMessage();
        // ----业务开始
        maintainService.maintainInfo(ifMessage);
        // ----业务结束
        Map<String, String> map = new HashMap<>();
        map.put("workOrderNo", info.getIfData().get(0).getWorkOrderNo());
        List<Map<String, String>> list = new ArrayList<>();
        list.add(map);
        String result = JSON.toJSONString(list);
        message.setIfCode(info.getIfCode());
        message.setTransferNo(info.getTransferNo());
        message.setResult("200");
        message.setResultList(result);
        return message;
    }
    
    @RequestMapping(value = "/insuranceExpireInfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "保险到期数据落地", notes = "保险到期数据落地")
    public Map<String,Object> insuranceExpireInfo() {
        Map<String,Object> resultMap = new HashMap<>();
        try{
        	resultMap = maintainService.insuranceExpireInfo();
            return resultMap;
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
    
    @RequestMapping(value = "/maintainExpire", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "保养到期提醒", notes = "保养到期提醒")
    public Map<String,Object> MaintainExpire() throws Exception{
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            resultMap = maintainService.maintainExpire();
            return resultMap;
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
    
    @RequestMapping(value = "/insuranceExpire", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "保险到期提醒", notes = "保险到期提醒")
    public Map<String,Object> insuranceExpire() throws Exception{
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            resultMap = maintainService.insuranceExpire();
            return resultMap;
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

}
